﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities.Admin;
using BLL.Admin;
using System.Collections;

namespace WindowsForms.Admin
{
    public partial class UcDsTaiKhoan : UserControl
    {
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        public StringFormat strFormat;
        public ArrayList arrColumnWidths = new ArrayList();
        public ArrayList arrColumnLefts = new ArrayList();
        public int iCount = 0;
        public bool State = true;
        public int nums = 10;
        public int page = 1;
        public int tong;
        public UcDsTaiKhoan()
        {
            InitializeComponent();
            btnprview.AutoGenerateColumns = false;

        }

        private void btnrefresh_Click(object sender, EventArgs e)
        {
            if (getPage(page).Count == 0)
                page = 0;
            LoadTaiKhoan(getPage(page));
        }
        private void LoadTaiKhoan(List<TaiKhoan> ds)
        {
            btnprview.DataSource = ds;
            tbdl.TextBox.Text = page + "/ " + tong;
        }

        private void dataGridViewtk_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 6)
                {
                    string dl = btnprview[0, e.RowIndex].Value.ToString();
                    TaiKhoan.Objects.Delete(p => p.UserName == dl);
                    LoadTaiKhoan(getPage(page));
                }
                if (e.ColumnIndex == 7)
                {
                    string us = btnprview[0, e.RowIndex].Value.ToString();
                    TaiKhoan tk = TaiKhoan.Objects.GetById(us);
                    if (tk != null)
                    {
                        NhanVien nv = NhanVien.Objects.GetById(tk.MaNhanVien);
                        string ns = nv.NamSinh.ToString("dd/MM/yy");
                        string pas = "";
                        string[] k = ns.Split('/');
                        foreach (var item in k)
                            pas += item;
                        TaiKhoan.Objects.Update(x => x.UserName == us, x => new TaiKhoan
                        {
                            Password = pas
                        });
                        List<TaiKhoan> ds = new List<TaiKhoan>() { tk };
                        LoadTaiKhoan(ds);



                    }
                }
            }
            catch (Exception)
            {
 
            }
          


        }
        public List<TaiKhoan> getPage(int page)
        {
            tong = ManagerForm.TongTrang(TaiKhoan.Objects.All().ToList().Count, nums);
            var query = from c in TaiKhoan.Objects.All().ToList()
                           .Skip(nums * page - nums).Take(nums)
                        select c;
            return query.ToList();


        }
        private void btntien_Click(object sender, EventArgs e)
        {

            if (page < tong)
                page++;

            if (page <= tong)
            {
                tbdl.TextBox.Text = page + " / " + tong;
                LoadTaiKhoan(getPage(page));

            }
        }

        private void btnlui_Click(object sender, EventArgs e)
        {
            if (page >= 2)
            {
                page--;
                tbdl.TextBox.Text = page + " / " + tong;
                LoadTaiKhoan(getPage(page));
            }
        }

        private void btnsapxep_Click(object sender, EventArgs e)
        {
            if (State)
            {
                List<TaiKhoan> ds = QuanLiTaiKhoan.SapTangTheoUsername(getPage(page));
                LoadTaiKhoan(ds);
                State = !State;
            }
            else
            {
                List<TaiKhoan> ds = QuanLiTaiKhoan.SapGiamTheoUsername(getPage(page));
                LoadTaiKhoan(ds);
                State = !State;

            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {
                    //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                    //{
                    //    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    //        (double)iTotalWidth * (double)iTotalWidth *
                    //        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    //    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    //        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    //    // Save width and height of headers
                    //    arrColumnLefts.Add(iLeftMargin);
                    //    arrColumnWidths.Add(iTmpWidth);
                    //    iLeftMargin += iTmpWidth;
                    //}
                    for (int k = 0; k < btnprview.ColumnCount - 2; k++)
                    {
                        iTmpWidth = (int)(Math.Floor((double)((double)btnprview.Columns[k].Width /
                            (double)iTotalWidth * (double)iTotalWidth *
                            ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(btnprview.Columns[k].HeaderText,
                            btnprview.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headers
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;
                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= btnprview.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = btnprview.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 5;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //Draw Header
                            e.Graphics.DrawString("Acount Customer",
                                new Font(btnprview.Font, FontStyle.Bold),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(btnprview.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate,
                                new Font(btnprview.Font, FontStyle.Bold), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(btnprview.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(new Font(btnprview.Font, FontStyle.Bold),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                            //{
                            //    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawRectangle(Pens.Black,
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawString(GridCol.HeaderText,
                            //        GridCol.InheritedStyle.Font,
                            //        new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            //        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            //    iCount++;
                            //}
                            for (int l = 0; l < btnprview.Columns.Count - 2; l++)
                            {
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(btnprview.Columns[l].HeaderText,
                                    btnprview.Columns[l].InheritedStyle.Font,
                                    new SolidBrush(btnprview.Columns[l].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;
                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        //foreach (DataGridViewCell Cel in GridRow.Cells)
                        //{
                        //    if (Cel.Value != null)
                        //    {
                        //        e.Graphics.DrawString(Cel.Value.ToString(),
                        //            Cel.InheritedStyle.Font,
                        //            new SolidBrush(Cel.InheritedStyle.ForeColor),
                        //            new RectangleF((int)arrColumnLefts[iCount],
                        //            (float)iTopMargin,
                        //            (int)arrColumnWidths[iCount], (float)iCellHeight),
                        //            strFormat);
                        //    }
                        //    //Drawing Cells Borders 
                        //    e.Graphics.DrawRectangle(Pens.Black,
                        //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        //        (int)arrColumnWidths[iCount], iCellHeight));
                        //    iCount++;
                        //}
                        for (int t = 0; t < GridRow.Cells.Count - 2; t++)
                        {
                            if (GridRow.Cells[t].Value != null)
                            {
                                e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                    GridRow.Cells[t].InheritedStyle.Font,
                                    new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount],
                                    (float)iTopMargin,
                                    (int)arrColumnWidths[iCount], (float)iCellHeight),
                                    strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iCellHeight));
                            iCount++;
                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }

        }




        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                //foreach (DataGridViewColumn dgvGridCol in dataGridViewtk.Columns)
                //{
                //    iTotalWidth += dgvGridCol.Width;
                //}
                for (int k = 0; k < btnprview.Columns.Count - 2; k++)
                {
                    iTotalWidth += btnprview.Columns[k].Width;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnin_Click(object sender, EventArgs e)
        {
            //PrintPreviewDialog printDialog = new PrintPreviewDialog();
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument1;
            printDialog.UseEXDialog = true;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }

        private void btnpr_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printDialog = new PrintPreviewDialog();
            //PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument1;
            //printDialog.UseEXDialog = true;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }


        private void btntimkiemtk_Click(object sender, EventArgs e)
        {
            FormTimKiemTaiKhoan fr = new FormTimKiemTaiKhoan();
            fr.FormClosed += new FormClosedEventHandler(fr_FormClosed);
            fr.ShowDialog();
        }

        void fr_FormClosed(object sender, FormClosedEventArgs e)
        {
            string data = FormTimKiemTaiKhoan.data;
            if (!String.IsNullOrWhiteSpace(data))
            {

                if (FormTimKiemTaiKhoan.state)
                {
                    List<TaiKhoan> ds = TaiKhoan.Objects.Find(p => p.UserName.Contains(data)).ToList();

                    if (ds.Count > 0)
                    {
                        LoadTaiKhoan(ds);

                    }
                    else
                    {
                        MessageBox.Show("Không Tìm Thấy");
                    }




                }
            }
        }


    }
}
